import { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import { AtLoadMore } from 'taro-ui'

import * as api from 'src/api'
import { EVENT_CHECK_STORE } from 'src/constants'
import withPage from 'src/utils/withPage'

import './index.scss'

type IProps = {}

type IState = {
  storeList: any[]
  listStatus?: 'more' | 'loading' | 'noMore'
}

interface Index {
  props: IProps
  state: IState
  fromConfirm: boolean
}

@withPage()
class Index extends Component {
  state: IState = {
    storeList: [],
    listStatus: 'more',
  }

  async componentDidMount() {
    await this.getStoreList()
  }

  onLoad(options) {
    this.fromConfirm = !!options.from_confirm
  }

  async onPullDownRefresh() {
    await this.getStoreList()
    Taro.stopPullDownRefresh()
  }

  getStoreList = async () => {
    this.setState({ listStatus: 'loading' })
    const res = await api.getStoreList()
    const list = res || []
    this.setState({
      storeList: list,
      listStatus: 'noMore',
    })
  }

  call = (phoneNumber) => {
    Taro.makePhoneCall({ phoneNumber })
  }

  handleChecke = (item) => {
    if (this.fromConfirm) {
      Taro.eventCenter.trigger(EVENT_CHECK_STORE, item)
      Taro.navigateBack()
    }
  }

  render() {
    const { storeList, listStatus } = this.state
    return (
      <View>
        <View className="store-list">
          {storeList.map((item) => (
            <View
              className="store-item at-row at-row__justify--between at-row__align--center"
              key={item.a}
            >
              <View className="store-info at-col">
                <View className="store-name">{item.name}</View>
                <View className="store-note">{item.address}</View>
                <View className="store-note">
                  电话：
                  <Text
                    className="store-phone"
                    onClick={() => this.call(item.telephone)}
                  >
                    {item.telephone}
                  </Text>
                </View>
              </View>
              <View
                className="row-right"
                onClick={() => this.handleChecke(item)}
              >
                去下单
              </View>
            </View>
          ))}
        </View>
        <AtLoadMore status={listStatus} noMoreTextStyle={{ fontSize: 12 }} />
      </View>
    )
  }
}

export default Index
